package com.igeek.car.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.car.entity.Checi;
import com.igeek.car.entity.XianLu;
import com.igeek.car.mapper.CheCiMapper;
import com.igeek.car.mapper.XianLuMapper;
import com.igeek.car.vo.PageQueryVO;
import com.igeek.car.service.XianLuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * TODO
 *
 * @author bbjs
 * @since 2024/12/4
 */

@Service
public class XianLuServicelmpl extends ServiceImpl<XianLuMapper, XianLu> implements XianLuService{

    @Autowired
    private  XianLuMapper xianLuMapper;
    @Autowired
    private CheCiMapper checiMapper;


    //分页查询条件
    @Transactional(readOnly = true)
    @Override
    public Page<XianLu> findPage(PageQueryVO vo) {
        //1.封装分页数据
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        Page<XianLu> page = Page.of(currentPage, pageSize);

        //2.封装查询条件
        String queryString = vo.getQueryString();
        LambdaQueryWrapper<XianLu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasLength(queryString) , XianLu::getRouteId , queryString)
                .or()
                .like(StringUtils.hasLength(queryString) , XianLu::getRouteName , queryString);


        //3.执行分页条件查询
        Page<XianLu> XianLuPage = this.page(page, lambdaQueryWrapper);
        return XianLuPage;
    }

    @Transactional
    @Override
    public boolean del(String id) {
        // 1. 检查线路是否存在
        if (ObjectUtils.isEmpty(id) || this.baseMapper.selectById(id) == null) {
            throw new RuntimeException("线路不存在！");
        }

        // 2. 获取线路的运营状态
        XianLu xianLu = this.baseMapper.selectById(id);  // 获取线路对象
        if (xianLu == null) {
            throw new RuntimeException("线路不存在！");
        }

        // 3. 检查线路是否在运营中
        if (Boolean.TRUE.equals(xianLu.getIsOperating())) {
            throw new RuntimeException("该线路正在运营中，无法删除！");
        }

        // 4. 查询调度表中是否存在相同的线路ID
        LambdaQueryWrapper<Checi> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Checi::getRouteId, id);  // 检查调度表中是否有相同的线路ID

        // 使用 checiMapper 来执行查询
        Long count = checiMapper.selectCount(queryWrapper);  // 获取符合条件的记录数

        if (count > 0) {
            throw new RuntimeException("该线路有正在进行的调度任务，无法删除！");
        }

        // 5. 执行删除操作
        int result = this.baseMapper.deleteById(id);
        return result > 0;
    }




}
